# -*- encoding: utf-8 -*-
'''
@describe: 读取MongoDB数据库的工具类
'''

# import MongoDB
import pymongo
from config import *


class MongoDBUtil:

    # def __init__(self):
    def __init__(self, db_section='db'):

        # config = configparser.RawConfigParser()
        # config.read('config.conf', encoding='utf-8')
        #
        # username = parse.quote_plus(config.get(db_section,'db_user'))   # 对用户名进行编码
        # password = parse.quote_plus(config.get(db_section,'db_password'))  # 对密码进行编码
        # host = config.get(db_section,'db_host')
        # port = int(config.get(db_section,'db_port'))
        # database = config.get(db_section,'db_database')

        # client = pymongo.MongoClient('mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, database))
        client = pymongo.MongoClient('mongodb://%s:%s@%s:%s/%s' % (DBUSRT, DBPASSWORD, DBHOST, DBPORT, DBDATABASE))
        self.client = client
        self.db = client[DBDATABASE]

        # self.client = pymongo.MongoClient(config.get(db_section,'db_host'), int(config.get(db_section,'db_port')))   # 本地IP，默认端口
        #
        # self.db = self.client[config.get(db_section,'db_database')]  # 进入数据库
        #
        # #如果mongo有密码，需进行登陆
        # db_user = parse.quote_plus(str(config.get(db_section,'db_user')))   # 对用户名进行编码
        # db_password = parse.quote_plus(str(config.get(db_section,'db_password')))  # 对密码进行编码
        # # db_user = config.get(db_section,'db_user')
        # # db_password = config.get(db_section,'db_password')
        # if db_user != None and db_user != '':
        #     self.db.authenticate(db_user , db_password)

    def insert_one(self, collectionName, document):
        col = self.db[collectionName]
        return col.insert_one(document)

    def insert_many(self, collectionName, documents):
        col = self.db[collectionName]
        if len(documents) > 0:
            return col.insert_many(documents)
        else:
            return None

    def update(self, collectionName, query, newvalues, updateMany=True):
        col = self.db[collectionName]
        if updateMany:
            return col.update_many(query, newvalues)
        else:
            return col.update_one(query, newvalues)

    def delete(self, collectionName, query, deleteMany=True):
        col = self.db[collectionName]
        if deleteMany:
            return col.delete_many(query)
        else:
            return col.delete_one(query)

    def find_one(self, collectionName, query={}, fileds={}):
        col = self.db[collectionName]
        if fileds == {}:
            return col.find_one(query)
        else:
            return col.find_one(query, fileds)

    def find(self, collectionName, query={}, fileds={}, limit=0):
        col = self.db[collectionName]

        res = []
        cursor = None

        if limit > 0:
            if fileds == {}:
                cursor = col.find(query).limit(limit)
            else:
                cursor = col.find(query, fileds).limit(limit)
        else:
            if fileds == {}:
                cursor = col.find(query)
            else:
                cursor = col.find(query, fileds)

        for obj in cursor:
            res.append(obj)

        return res

    def limit_find_one(self, collectionName, query={}, skip=0, limit=0):
        col = self.db[collectionName]

        res = []
        cursor = None

        if limit > 0:
            cursor = col.find(query).skip(skip).limit(limit)
        for obj in cursor:
            res.append(obj)

        return res

    def update(self, collectionName, criteria={}, query={}):
        col = self.db[collectionName]
        return col.update_one(criteria, query)

    def close(self):
        """close db connect
        """
        self.client.close()

# if __name__ == '__main__':
#     mongoHelper = MongoDBUtil()
#     # 从数据库中获取该俩个对比文件相识的内容,分值大于0.8的,根据文件id查询
#     dataList = mongoHelper.find("similarity",
#                                 {"reportId": "14", "sFileId": "19023",
#                                  "tFileId": "34178", "sim": {"$gte": 0.9},
#                                  "source": {"$exists": "true"}, "$where": "this.source.length>15",
#                                  "target": {"$exists": "true"}, "$where": "this.target.length>15"
#                                  })
#
#     print(len(dataList))
